<%@page import="java.io.File"%>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Set"%>
<%@page import="java.util.HashMap"%>
<%@page import="org.apache.solr.client.solrj.response.FacetField"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="ibase.solr.formatter.SearchFormatter"%>
<%@page import="java.io.ByteArrayInputStream"%>
<%@page import="javax.xml.transform.stream.StreamSource"%>
<%@page import="javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.Result"%>
<%@page import="javax.xml.transform.dom.DOMSource"%>
<%@page import="javax.xml.transform.Source"%>
<%@page import="org.xml.sax.InputSource"%>
<%@page import="javax.xml.transform.Transformer"%>
<%@page import="javax.xml.transform.TransformerFactory"%>
<%@page import="org.apache.solr.common.SolrInputDocument"%>
<%@page import="org.apache.solr.client.solrj.util.ClientUtils"%>
<%@page import="org.apache.solr.common.SolrDocument"%>
<%@page import="org.apache.solr.common.SolrDocumentList"%>
<%@page import="org.apache.solr.client.solrj.response.QueryResponse"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search Detail</title>
<link type="text/css"  rel ="stylesheet"  href="/SolrQMSApplication/css/SolrQms.css">
<script type="text/javascript">
function callPage( aElement )
{
	try {
		
		var urlToPass = aElement.getAttribute("CustomUrl");
		parent.document.getElementById("detail").src = urlToPass;
	} catch (e) {
		alert("Exception: " + e);
	}
}
function callFacetList( anchorElement )
{
	try {
		var urlToPass = anchorElement.getAttribute("CUSTOM");
		parent.document.getElementById("detail").src = urlToPass;
	} catch (e) {
		alert("Exception: " + e);
	}
}
</script>
</head>
<body>
<!-- h3>Search Detail</h3-->
<form name="SearchDetailForm" >
<div id="dataDiv" class="dataClass">
<% 
	HttpSession solrSession= request.getSession();
	long totalPages =0;
	QueryResponse queryResponse = (QueryResponse) solrSession.getAttribute("solrResponse");
	String queryString = (String) solrSession.getAttribute("queryString");
	String uri=(String) solrSession.getAttribute("requestUri");
	SolrDocumentList docs = queryResponse.getResults();
	HashMap objDescMap =new HashMap();
	if (docs != null)
	{
	 	totalPages =(docs.getNumFound()/10); 
%>
<span id="detailHeader" class="detailHeaderClass"><%= docs.getNumFound()%> records found</span><br>
<hr width="1000px" align="left"><BR>
<%
	try {
		
		
		for (int i = 0; i < docs.size(); i++) 
		{
				SolrDocument doc = docs.get(i);
				System.out.println("doc : [ "+doc.getFieldNames()+" ]");
				String objName = (String) doc.getFieldValue("SCATNAME");
				String objDesc = (String) doc.getFieldValue("SDESCRIPTION");
				System.out.println("objName : [ "+objName+" ] objDesc:[ "+objDesc+" ]");
				SolrInputDocument soltInputDoc = ClientUtils.toSolrInputDocument(doc);
				String xmlString = ClientUtils.toXML(soltInputDoc);
				StreamSource source = new StreamSource(new ByteArrayInputStream(xmlString.getBytes()));
				if(objName != null)
				{	
					String xslString = SearchFormatter.getXSL(application.getRealPath("/")+File.separator+"xsl"+File.separator+"changecontrol.xsl");
					StreamSource stylesource = new StreamSource(new ByteArrayInputStream(xslString.getBytes()));
					TransformerFactory factory = TransformerFactory.newInstance();
			      	Transformer transformer = factory.newTransformer(stylesource);
			        	StreamResult result = new StreamResult(out);
			        	transformer.transform(source, result);
				}
				else
				{
					continue;
				}
%><hr width="1000px" align="left"><BR>
<% 
		}
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	}
	
	Pattern p = Pattern.compile("pageNo=([^&]+)");
	Matcher m = p.matcher(queryString);
	String prvPageNo="";
	while(m.find()){
		prvPageNo = m.group(1);
	}
	
	int prvPageNoInt= Integer.parseInt(prvPageNo);
	String queryStringNext=queryString.replaceAll("pageNo="+prvPageNo, "pageNo="+((prvPageNoInt)+2));
	String queryStringPaginate=queryString;
	String urlPrv = uri+"?"+queryString;
	String urlNxt = uri+"?"+queryStringNext;
	long startIndex =((prvPageNoInt-4) > 0)?(prvPageNoInt-4):0;
	long endIndex =(startIndex+10)>totalPages ? totalPages:startIndex+10;
%>
<a onclick=callPage(this); href="#" CustomUrl="<%=urlPrv%>">Prv</a>&nbsp;
<% for(long i = startIndex; i<endIndex ; i++)
	{
		queryStringPaginate=queryStringPaginate.replaceAll("pageNo="+prvPageNo, "pageNo="+i);
		String url = uri+"?"+queryStringPaginate;
		prvPageNo=String.valueOf(i);
%>		
<a onclick=callPage(this); href="#" CustomUrl="<%=url%>"><%=i+1 %></a>&nbsp;
<% 	
	}
%>
<a onclick=callPage(this); href="#" CustomUrl="<%=urlNxt%>">Next</a>&nbsp;
</div>
<div id="filterDiv" class="filterClass">
<%
	List<FacetField> facetFields = queryResponse.getFacetFields();
	Iterator<FacetField> facetFieldIterator = facetFields.iterator();
	String tmpUrl ="";
	ArrayList removeLinkList = new ArrayList();
	while(facetFieldIterator.hasNext()) 
	{
		FacetField facetField = facetFieldIterator.next();
		String facetNameDisp="";
		if(facetField.getName().equalsIgnoreCase("SCATNAME"))
		{
			facetNameDisp="Form Category";
		}
		else if(facetField.getName().equalsIgnoreCase("site_code"))
		{
			facetNameDisp="Site";
		}
%>
<BR><span id="facetName" class="facetNameClass"><li><%=facetNameDisp %></li></span><ul> 
<% 	
		List<FacetField.Count> facetFieldCounts = facetField.getValues();
		Iterator<FacetField.Count> facetFieldCountIterator = facetFieldCounts.iterator();
		boolean hasQueryString = false;
		String facetValueDisp="";
		while(facetFieldCountIterator.hasNext())
		{
			FacetField.Count count = facetFieldCountIterator.next();
			StringBuffer stringBuffer = new StringBuffer("?");
			
			if(queryString != null) 
			{
				queryString=queryString.replaceAll("pageNo="+prvPageNoInt,"pageNo="+0);
				stringBuffer.append(queryString);
				hasQueryString = true;
			}
			if(hasQueryString) 
			{
				stringBuffer.append("&");
			}
			stringBuffer.append(facetField.getName() + "=" + count.getName());
			removeLinkList.add(facetField.getName() + "=" + count.getName());
			tmpUrl = uri + stringBuffer.toString();
%>
<span id="facetValue" class ="facetValueclass" ><li><a onclick=callFacetList(this); href="#" CUSTOM="<%=tmpUrl%>"><%= facetField.getName().equalsIgnoreCase("site_code")?count.getName().toUpperCase():count.getName() %> ( <%=count.getCount() %>)</a></li></span>
<%		
					
		//	}
				
		}
%>		
</ul></li>
<%		
	}
%><span id="selectedFacetName" class="facetNameClass">Filter on :</span> 
<%	
	Iterator linkIterator = removeLinkList.iterator();

	while(linkIterator.hasNext())
	{
		String facetNameValuePair = (String) linkIterator.next();
		String facetValue = facetNameValuePair.substring(facetNameValuePair.indexOf("=")+1);
		if(null != queryString) 
		{
			String removeLink = "";
			removeLink = uri + "?" + queryString;
			if(null != queryString && queryString.contains(facetNameValuePair))
			{	
				removeLink = removeLink.replaceAll(facetNameValuePair, "");

%>
<span id="selectedFacetValue" class ="facetValueclass" ><%= facetValue %></span><a onclick=setVisibility(this); href= "<%=removeLink%>"><img id="removeImage" src="/SolrQMSApplication/images/cancel.png" style="visibility: visible;"/></a>			
<% 			
			}
		}
	}
%>
</div>
</form>
</body>
</html>